#include <pthread.h>
#include "lightswitch.h"

void lightswitch_init(lightswitch_t *switcher) {
    pthread_mutex_init(&(switcher->mutex), NULL);
    pthread_mutex_init(&(switcher->switcher), NULL);
    pthread_mutex_init(&(switcher->count_mutex), NULL);
    switcher->type = 0;
    switcher->count = 0;
}

void lightswitch_lock(lightswitch_t *switcher, unsigned int type) {
    pthread_mutex_lock(&(switcher->mutex));
        if ((! switcher->count) || (switcher->type != type)) {
            pthread_mutex_lock(&(switcher->switcher));
            switcher->type = type;
        }
        pthread_mutex_lock(&(switcher->count_mutex));
            switcher->count++;
        pthread_mutex_unlock(&(switcher->count_mutex));
    pthread_mutex_unlock(&(switcher->mutex));
}

void lightswitch_unlock(lightswitch_t *switcher) {
    pthread_mutex_lock(&(switcher->count_mutex));
        switcher->count--;
        if (! switcher->count)
            pthread_mutex_unlock(&(switcher->switcher));
    pthread_mutex_unlock(&(switcher->count_mutex));
}
